package hibernatelogic;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import orm.Items;
import testpackage.testclass;
import utils.HibernateUtil;

/**
 * 
 * @author Igor Petrov
 * The DAO class for ITEMS table
 *
 */

public class HibItems {
	
	public HibItems(){}
	
	/**
	 * select * from items;
	 * @throws SQLException
	 */
	public Collection getAllItems() throws SQLException {
		session = null;
		List items = new ArrayList<Items>();
		try {
			session = hibUtil.getSessionFactory().openSession();
			items = session.createCriteria(Items.class).list();
		} catch (Exception e) {
			loggerHibItems.error("getAllItems failed!!!", e);
		} finally {
			if(session != null && session.isOpen()){
				session.close();
			}
		}
		return items;
	}
	
	/**
	 * insert into items values([item])
	 * @param item
	 * @throws SQLException
	 */
	public void addItem(Items item) throws SQLException {
		session = null;
		try {
			session = hibUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(item);
			session.getTransaction().commit();
		} catch (Exception e) {
			loggerHibItems.error("addItem failed!!!", e);
			session.getTransaction().rollback();
		} finally {
			if (session != null && session.isOpen()){
				session.close();
			}
		}
	}
	
	/**
	 * delete from items where ['item' = item]
	 * @param item
	 * @throws SQLException
	 */
	public void deleteItem(Items item) throws SQLException {
		try {	
			session = null;
			session = hibUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(item);
			session.getTransaction().commit();
		} catch (Exception e) {
			loggerHibItems.error("deleteItem  failed!!!", e);
			session.getTransaction().rollback();
		} finally {
			if(session != null && session.isOpen()){
				session.close();
			}
		}
	}
	
	/**
	 * select * from items where item_id = 'item_id'
	 * @param item_id
	 * @return
	 * @throws SQLException
	 */
	public Items getItemByID (int item_id) throws SQLException {
		session = null;
		Items item = null;
		try {
			session = hibUtil.getSessionFactory().openSession();
			session.beginTransaction();
			item = (Items) session.get(Items.class, item_id);
		} catch (Exception e) {
			loggerHibItems.error("getItemByID failed!!!", e);
		} finally {
			if(session != null && session.isOpen()){
				session.close();
			}
		}
		return item;
	}
	
	HibernateUtil hibUtil = new HibernateUtil();
	private Session session = null;
	private static final Logger loggerHibItems = Logger.getLogger(HibItems.class); 
}
